package com.cucn.ingmall.seckill.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.cucn.common.constant.auth.SmsConstant;
import com.cucn.common.to.dto.MemberResponseDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 订单登录拦截
 *
 * @author KouChaoJie
 * @since: 2022/1/19 09:50
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberResponseDTO> loginUser = new ThreadLocal<>();

    /**
     * 订单方法执行之前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //当前请求地址
        if (relaseUrl(request)) {
            HttpSession session = request.getSession();
            MemberResponseDTO member = (MemberResponseDTO) session.getAttribute(SmsConstant.LOGIN_USER);

            if (ObjectUtil.isNotEmpty(member)) {
                //已登录,放行
                loginUser.set(member);

                return true;
            } else {
                //未登录,让用户登录
                session.setAttribute("msg", "请先登录");
                response.sendRedirect("http://auth.koukoucoding.xn--fiqs8s/login.html");

                return false;
            }
        }
        return true;

    }

    private boolean relaseUrl(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        return antPathMatcher.match("/kill", requestURI);
    }
}
